import { trim } from "lodash";
import React, { useState } from "react";
import PropTypes from "prop-types";
import Widget from "./Widget";
import location from "@/services/location";
import { replaceUrlParameter } from "@redash/viz/lib/lib/DateRangeParameter";
import HtmlContent from "@redash/viz/lib/components/HtmlContent";

function UrlWidgetHeader({ widget }) {
  const title = replaceUrlParameter(widget.getWidgetOptions("widget_title"));
  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_titlecolor');

  return (!!trim(title)) && (
    <div className="t-header widget clearfix"
      style={showPortal ? {
        background: localStorage.getItem('colorstyle_titleback'), 
        color: localStorage.getItem('colorstyle_titlecolor'),
        height: '40px',
      } : {height: '40px'}}
    >
      <div className="th-title" style={!!widget.getWidgetOptions("title_center") ? {textAlign:'center',float: 'middle'} : {float: 'left'}}>  
        <span style={showPortal ? {color: localStorage.getItem('colorstyle_titlecolor')} : null}>
          <HtmlContent>{title}</HtmlContent>
        </span>
      </div>
    </div>
  );
}

function UrlWidget(props) {
  const { widget } = props;
  const [refreshStartedAt, setRefreshStartedAt] = useState(widget.refreshStartedAt);
  // const hide_scrolling = widget.getWidgetOptions("hide_scrolling") || false;
  const hide_scrolling = widget.getWidgetOptions("widget_noscroll") || false;
  const bgTransparent = widget.getWidgetOptions("widget_bgtransparent") || false;
  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_titlecolor');

  if (!!!refreshStartedAt && !!widget.refreshStartedAt) {
    setRefreshStartedAt(widget.refreshStartedAt);
  } else if (!!refreshStartedAt && !!widget.refreshStartedAt) {
    if (refreshStartedAt.isBefore(widget.refreshStartedAt)) {
      setRefreshStartedAt(widget.refreshStartedAt);
    }
  }

  let url = widget.getWidgetOptions("url");
  if (showPortal) {
    if (url.includes('?')) url = url + '&';
    else url = url + '?';
    
    url = url + location.getStyleUrl();
  }
  url = encodeURI(url);

  if (!widget.width) {
    return null;
  }

  return (    
    <Widget 
      {...props} 
      className="widget-text"
      header={<UrlWidgetHeader widget={widget} />
      }
    >
      <iframe
        title="Redash_Widget"
        sandbox="allow-same-origin allow-top-navigation allow-forms allow-scripts allow-popups"
        frameBorder="0"
        width="100%"
        height="100%"
        allowTransparency={bgTransparent}
        scrolling={hide_scrolling ? "no" : "auto"}
        src={url}      
      />  
    </Widget>
  );
};

UrlWidget.propTypes = {
  widget: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

export default UrlWidget;
